package com.ruoyi.common.mp.hander;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

@Slf4j
@Component   //一定不要忘记将处理器加到IOC容器中！
public class MyMetaObjectHander implements MetaObjectHandler {

    //插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill.....");
        // 验证toke是否存在 anonymousUser: 匿名访问用户
        if (!Objects.equals("anonymousUser", SecurityUtils.getAuthentication().getPrincipal())) {
            //setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
            //第一个参数 字段名
            //第二个参数 值
            //第三个参数 metaObject
//        this.setFieldValByName("createTime",new Date(),metaObject);
//        this.setFieldValByName("updateTime",new Date(),metaObject);
            // 上面的方法是旧版本，新版本的是使用下面的strictInsertFill方法
            String username = SecurityUtils.getUsername();
            this.strictInsertFill(metaObject, "createBy", String.class, username);

        }
        this.strictInsertFill(metaObject, "createTime", Date.class, DateUtils.getNowDate());
    }

    //更新时的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill.....");
        // 验证toke是否存在 anonymousUser: 匿名访问用户
        if (!Objects.equals("anonymousUser", SecurityUtils.getAuthentication().getPrincipal())) {
            String username = SecurityUtils.getUsername();
            this.strictUpdateFill(metaObject, "updateBy", String.class, username);
        }
        this.strictUpdateFill(metaObject, "updateTime", Date.class, DateUtils.getNowDate());
    }
}

